package com.ysstech.reportworld.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.fileutil.FileUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.reportworld.entity.SqlScript;
import com.ysstech.reportworld.entity.DemandBugInfo;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
@Api(tags = "报表世界脚本管理api")
@RequestMapping("/sqlScript")
public class SqlScriptController extends BaseController {

    @Autowired
    private SqlScriptService sqlScriptService;
    @Autowired
    private ModularService modularService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private DemandBugInfoService demandBugInfoService;

    /**
     * 跳转报表世界脚本管理页面
     *
     * @return
     * @throws Exception
     */
    @YssPermissions(value = {"reportworld:sqlScript"})
    @ApiOperation(value = "跳转报表世界脚本管理页面")
    @YssLog(module = "报表世界脚本管理", remark = "跳转报表世界脚本管理页面")
    @RequestMapping(value = "/page")
    public String page(HttpServletRequest request) throws Exception {
        request.setAttribute("user", redisCacheManager.getLoginUserInfo());
        return "reportworld/sqlScript";
    }


    @YssPermissions(value = {"reportworld:sqlScript"})
    @ApiOperation(value = "获取报表世界脚本管理页面初始值")
    @YssLog(module = "报表世界脚本管理", remark = "获取报表世界脚本管理页面初始值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 所属模块
        List<TreeNode> listModular = modularService.queryModularTree();
        TreeNode treeNode = new TreeNode();
        treeNode.setId("");
        treeNode.setText("==请选择==");
        treeNode.setPId("0");
        treeNode.setIconCls("icon-bricks");
        map.put("listModular", listModular);
        listModular.add(0, treeNode);
        map.put("listModular2", listModular);
        // 所属客户
        List<TreeNode> listCustomer = customerService.queryCustomerTree();
        map.put("listCustomer", listCustomer);
        listCustomer.add(0, treeNode);
        map.put("listCustomer2", listCustomer);
        // 所属报表
        List<TreeNode> listReport = reportService.queryReportTree();
        map.put("listReport", listReport);
        listReport.add(0, treeNode);
        map.put("listReport2", listReport);
        // 版本
        List<Dicvalue> listVersion = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_VERSION.getCode());
        map.put("listVersion", listVersion);
        map.put("listVersion2", listVersion);
        // 能够还原的版本
        List<Dicvalue> listReductionVersion = sqlScriptService.getReductionVersion();
        map.put("listReductionVersion", listReductionVersion);
        // 报表世界所在分层
        List<Dicvalue> listLayered = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_TABLE_LAYERED.getCode());
        map.put("listLayered", listLayered);
        map.put("listLayered2", listLayered);
        // 当前版本的所有需求和BUG
        List<DemandBugInfo> demandBugInfoList = demandBugInfoService.selectByPrimaryByVersion();
        map.put("demandBugInfoList", demandBugInfoList);
        map.put("demandBugInfoList2", demandBugInfoList);
        // 数据库类型
        List<Dicvalue> listReportDataBaseType = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_DATABASE_TYPE.getCode());
        map.put("listReportDataBaseType", listReportDataBaseType);
       /* // SQL类型
        List<Dicvalue> ftype = dicValueService.getCacheDicValueList(ReportWorldEnum.DATASQL.getCode());
        map.put("ftype", ftype);
        map.put("ftype2", ftype);*/
        // 状态
        List<Dicvalue> listStatus = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_STATUS.getCode());
        map.put("listStatus", listStatus);
        map.put("listStatus2", listStatus);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }

    /**
     * SQL列表查询
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript"})
    @ApiOperation(value = "获取所有脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "获取所有脚本管理")
    @PostMapping(value = "/listInfo")
    @ResponseBody
    public RestResult listInfo(SqlScript sqlScript, String page, String rows) throws Exception {
        return ResultGenerator.getSuccessResult("获取所有脚本管理成功",
                sqlScriptService.queryAllSqlScripts(sqlScript, this.getPage(page, rows)));
    }

    /**
     * 新增SQL的方法
     *
     * @param sqlScript
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:add"})
    @ApiOperation(value = "新增脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "新增脚本管理")
    @RequestMapping(value = "/addSqlScript")
    @ResponseBody
    public RestResult addSqlScript(SqlScript sqlScript) throws Exception {
        sqlScriptService.addSqlScript(sqlScript);
        return ResultGenerator.getSuccessResult("新增脚本管理成功！");
    }

    /**
     * 修改脚本管理
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:edit"})
    @ApiOperation(value = "修改脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "修改脚本管理")
    @RequestMapping(value = "/editSqlScript")
    @ResponseBody
    public RestResult editSqlScript(SqlScript sqlScript) throws Exception {
        sqlScriptService.editSqlScript(sqlScript);
        return ResultGenerator.getSuccessResult("修改脚本管理成功！");
    }

    @ApiOperation(value = "检查脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "检查脚本管理")
    @RequestMapping(value = "/checkSqlScript")
    @ResponseBody
    public RestResult checkSqlScript(SqlScript sqlScript) throws Exception {
        String msgInfo = sqlScriptService.checkSqlScript(sqlScript);
        return ResultGenerator.getSuccessResult("检查脚本成功！", msgInfo);
    }

    /**
     * 删除脚本管理
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:del"})
    @ApiOperation(value = "删除脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "删除脚本管理")
    @RequestMapping(value = "/delSqlScript")
    @ResponseBody
    public RestResult delSqlScript(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        List<String> idList = JSONArray.parseArray(ids, String.class);
        if (CollectionUtils.isEmpty(idList)) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        sqlScriptService.removeByIds(idList);
        return ResultGenerator.getSuccessResult("删除脚本管理成功！");
    }


    /**
     * 脚本管理读取脚本文件
     *
     * @return
     */
    @ApiOperation(value = "脚本管理读取脚本文件")
    @YssLog(module = "报表世界脚本管理", remark = "脚本管理读取脚本文件")
    @RequestMapping(value = "/sqlScriptReadFile")
    @ResponseBody
    public RestResult sqlScriptReadFile(MultipartFile multipartfile) throws Exception {
        StringBuffer buffer = new StringBuffer();
        List<Object> list = FileUtil.readerTxt(multipartfile);
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("获取文件信息为空，请检文件！");
        }
        for (Object obj : list) {
            if (null == obj) {
                continue;
            }
            buffer.append(obj).append("\r\n");
        }
        return ResultGenerator.getSuccessResult("脚本管理读取脚本文件成功！", buffer);
    }

    /**
     * 审核脚本管理
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:process"})
    @ApiOperation(value = "审核脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "审核脚本管理")
    @RequestMapping(value = "/processSqlScript")
    @ResponseBody
    public RestResult processSqlScript(String ids) throws Exception {
        Map<String, String> map = new HashMap<>();
        String msgInfo = sqlScriptService.processSqlScript(ids);
        map.put("msgInfo", msgInfo);
        return ResultGenerator.getSuccessResult("审核脚本成功！", map);
    }

    /**
     * 审核退回脚本管理
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:rebut"})
    @ApiOperation(value = "审核退回脚本管理")
    @YssLog(module = "报表世界脚本管理", remark = "审核退回脚本管理")
    @RequestMapping(value = "/rebutSqlScript")
    @ResponseBody
    public RestResult rebutSqlScript(String ids, String msg) throws Exception {
        sqlScriptService.rebutSqlScript(ids, msg);
        return ResultGenerator.getSuccessResult("审核退回脚本成功！");
    }


    /**
     * 审核退回脚本管理
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:reduction"})
    @ApiOperation(value = "还原版本管理")
    @YssLog(module = "报表世界脚本管理", remark = "还原版本管理")
    @RequestMapping(value = "/reductionData")
    @ResponseBody
    public RestResult reductionData(String reductionVersion) throws Exception {
        if (StringUtils.isBlank(reductionVersion)) {
            throw new BusinessException("获取脚本管理数据失败，请稍后重试！");
        }
        sqlScriptService.reductionData(reductionVersion);
        return ResultGenerator.getSuccessResult("还原版本成功！");
    }


    /**
     * 导出脚本文件版本管理
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:sqlScript:down"})
    @ApiOperation(value = "导出脚本文件版本管理")
    @YssLog(module = "报表世界脚本管理", remark = "导出脚本文件版本管理")
    @RequestMapping(value = "/downSqlScriptFile")
    @ResponseBody
    public RestResult downSqlScriptFile(HttpServletResponse response, String ids) throws Exception {
        sqlScriptService.downSqlScriptFile(response, ids);
        return ResultGenerator.getSuccessResult("导出脚本文件版本管理成功！");
    }

}
